<template>
<div class="m-content">
  <h3>欢迎来到小天学习博客</h3>
  <div class="block">
    <el-avatar :size="50" :src="user.avatar"></el-avatar>
    <div>{{user.username}}</div>
  </div>

  <div class="maction">
    <span><el-link href="/blogs">主页</el-link></span>
    <el-divider direction="vertical"></el-divider>
    <span><el-link type="success" href="/blog/add">发表博客</el-link></span>
    <el-divider direction="vertical"></el-divider>

    <!--定义logout方法，将前端user的相关token和userInfo删除-->
    <span>
      <span v-show="!hasLogin">
        <el-link type="danger" @click="login">登录</el-link>
      </span>
      <span v-show="hasLogin">
        <el-link type="danger" @click="logout">退出</el-link>
      </span>
    </span>
  </div>

</div>

</template>

<script>
export default {
  name: "Header",
  //用户信息存入data
  data(){
    return{
      user:{
        username:'login pleases',
        avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      },
      hasLogin: false
    }
  },
  methods:{
    logout(){
      //现请求后端再删
      const _this = this
      //首先调用后端logout接口(因该接口需要认证权限,所以需要传入token)
      //其次调用$store清除用户信息及token
      //有两种情况，1.未登录就不需要调后端，要不然会报错2.登录了有状态信息了
      _this.axios.get("/logout",{
        headers:{
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        _this.$store.commit("REMOVE_INFO")
        _this.$router.push("/login")
      })
    },
    login(){//跳转登录页面进行登录
      this.$router.push("/login")
    }
  },
  //注意，该方法是在method外面的
  //页面创建时即会调用,进而获取用户信息
  created(){
    //如果用户存在
    if(this.$store.getters.getUser.username){
      this.user.username = this.$store.getters.getUser.username
      this.user.avatar = this.$store.getters.getUser.avatar
      //判断是登录状态还是非登录显示 退出按钮或者登录按钮
      this.hasLogin = true
    }
  }
}
</script>

<style scoped>

.m-content{
  max-width: 960px;
  margin: 0 auto;
  text-align: center;
}

.maction{
  margin: 10px 0;

}

</style>